package com.gameShare.utils

import java.security.MessageDigest
import java.util.regex.Pattern


class StringUtils {

    companion object {

        val VALID_PATH_PATTERN: Pattern = Pattern.compile("^[a-zA-Z0-9_/.-]+$")

        /**
         * 生成随机用户id
         * 这个生成是取决于随机的字母与数字序列
         * @return 用户id
         * @throws IllegalStateException
         */
        fun generateRandomUserId(length : Int) : String{
            if (length > 100)
                throw IllegalStateException("递归深度超过100")
            return generateRandomUserId(length, "")
        }

        /**
         * 生成随机userId的递归实现
         *
         * @param length 长度
         * @param text 初始文本
         * @return
         */
        fun generateRandomUserId(length: Int,text : String): String {
            return if (length == 0) text
            else generateRandomUserId(
                length - 1,
                when(RandomUtils.randomBool()){
                        true -> text + RandomUtils.randomChar()
                        false -> text + RandomUtils.randomNumber()
                    }
            )
        }

        /**
         * 对字符串生成md5
         *
         * @param str 字符串
         * @return md5化的字符串
         */
        fun md5(str : String) : String{
            val bytes = MessageDigest.getInstance("MD5").digest(str.toByteArray())
            return bytes.joinToString("") {
                "%02x".format(it)
            }
        }

        fun snakeCaseToCamelCase(str: String): String {
            return str.split("_")
                .mapIndexed { index, word ->
                    if (index == 0) word.lowercase()
                    else word.lowercase().replaceFirstChar { it.uppercase() }
                }
                .joinToString("")
        }

        @JvmStatic
        fun main(args: Array<String>) {
            println(generateRandomUserId(10))
        }

        fun checkPathIsOk(path: String?): Boolean {
            if (path.isNullOrBlank()) {
                return false
            }
            return !(path.contains("../") || path.contains("..\\") || !VALID_PATH_PATTERN.matcher(path).matches())
        }

    }



}